package bll

import (
	log "auth/collector/logger"
	"auth/errors"
	"auth/event"
	"auth/model"
	"auth/model/entity"
	"auth/store"
	"auth/store/postgres"
	"context"
	"gorm.io/gorm"
	"time"
)

type job struct {
	iJob     store.IJob
	iUserJob store.IUserJob
}

var Job = &job{}

func (a *job) init() func() {
	a.iJob = postgres.Job
	a.iUserJob = postgres.UserJob
	return func() {}
}

func (a *job) onEvent(*event.Data) {}

func (a *job) Create(ctx context.Context, in *model.JobCreateRequest) error {
	var (
		err error
	)
	err = isDuplicateJobName(0, in.JobName)
	if err != nil {
		return err
	}
	c := buildJob(in)
	_, err = a.iJob.Create(c)
	return err
}

func (a *job) Update(in *model.JobUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)
	f, err := a.iJob.Find(in.JobId)
	if err != nil {
		return err
	}
	if f.JobId <= 0 {
		return errors.NoData.Error()
	}
	err = isDuplicateJobName(in.JobId, in.JobName)
	if err != nil {
		return err
	}
	dict["job_name"] = in.JobName
	dict["updated_at"] = time.Now().Unix()
	return a.iJob.Update(in.JobId, dict)
}

func (a *job) Delete(in *model.JobDeleteRequest) error {
	cnt, err := a.iUserJob.CheckJobExistUser(in.ID)
	if err != nil {
		log.Error(err)
		return err
	}
	if cnt > 0 {
		return errors.JobUseProhibitDel.Error()
	}
	return a.iJob.Delete(in.ID)
}

func (a *job) List(in *model.JobListRequest) (*model.JobListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.Job
		out   = &model.JobListResponse{}
	)

	if total, list, err = a.iJob.List(in); err != nil {
		return nil, err
	}

	out.Total = total
	out.Data = model.JobsEntityToDto(list)

	return out, err
}

// isDuplicateJobName 验证是否重名
func isDuplicateJobName(jobId int64, jobName string) error {
	err := Job.iJob.IsExistJobName(jobId, jobName)
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return err
	}
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		return errors.JobExitsSameName.Error()
	}
	return nil
}

func buildJob(in *model.JobCreateRequest) *entity.Job {
	return &entity.Job{

		JobName: in.JobName,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
